package com.dal.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class RobustJsonParser {
    public static void main(String[] args) throws Exception {
        String filePath = "/Users/jian/Desktop/registry/1.txt";

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 读取文件中的原始字符串
            String rawJson = new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(filePath)));
            List<Object> myObjects = objectMapper.readValue(new File(filePath), objectMapper.getTypeFactory().constructCollectionType(List.class, Object.class));

            // 将无效的JSON格式转换为有效格式
            //String validJson = rawJson.replaceAll("([:,])\\s*(\\w+)(?=[,}])", "$1\"$2\"");

            // 读取有效的JSON并解析为Map对象
            //Object data = objectMapper.readValue(validJson, Object.class);

            // 输出读取到的集合
            for (Object obj : myObjects) {
                System.out.println(obj);
            }

            // 输出解析后的数据
//            System.out.println("读取到的数据: " + data);
        } catch (IOException e) {
            System.out.println("读取文件或解析JSON时发生错误: " + e.getMessage());
        }

    }

    private static String readFileContent(String filePath) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        }
        return sb.toString().replaceAll("//.*", ""); // 去除行注释
    }

    private static List<Map<String, Object>> parseContent(String content) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 增强的对象匹配正则（支持多行和嵌套）
        Pattern objectPattern = Pattern.compile(
            "\\{(?:[^{}]|\\{(?:[^{}]|\\{[^{}]*\\})*\\})*\\}", 
            Pattern.DOTALL | Pattern.MULTILINE);

        Matcher matcher = objectPattern.matcher(content);
        
        // 字段解析正则（支持多种数据类型）
        Pattern fieldPattern = Pattern.compile(
            "(\\w+)\\s*:\\s*" +
            "(?:" +
            "'((?:\\\\'|[^'])*+)'|" +    // 单引号字符串
            "\"((?:\\\\\"|[^\"])*+)\"|" + // 双引号字符串
            "([+-]?\\d+\\.?\\d*)|" +     // 数字
            "(true|false)|" +            // 布尔值
            "(null)" +                   // null
            ")(?=\\s*[,}])",            // 前瞻断言确保正确结束
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

        while (matcher.find()) {
            Map<String, Object> obj = new LinkedHashMap<>();
            String objectContent = matcher.group();
            
            Matcher fieldMatcher = fieldPattern.matcher(objectContent);
            while (fieldMatcher.find()) {
                String key = fieldMatcher.group(1);
                String singleQuote = fieldMatcher.group(2);
                String doubleQuote = fieldMatcher.group(3);
                String number = fieldMatcher.group(4);
                String bool = fieldMatcher.group(5);
                String nul = fieldMatcher.group(6);

                Object value = parseValue(singleQuote, doubleQuote, number, bool, nul);
                obj.put(key, value);
            }
            if (!obj.isEmpty()) {
                result.add(obj);
            }
        }
        return result;
    }

    private static Object parseValue(String sq, String dq, String num, String bool, String nul) {
        if (sq != null) {
            return sq.replace("\\'", "'");
        }
        if (dq != null) {
            return dq.replace("\\\"", "\"");
        }
        if (num != null) {
            return num.contains(".") ? Double.parseDouble(num) : Long.parseLong(num);
        }
        if (bool != null) {
            return Boolean.parseBoolean(bool);
        }
        if (nul != null) {
            return null;
        }
        throw new IllegalArgumentException("无法识别的值类型");
    }
}